from django.contrib import admin
from .models import Employee

@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
    """
    统一的员工管理界面，根据角色标识显示不同字段
    """
    list_display = ['get_identifier', 'username', 'name', 'get_role_display', 'department', 'position', 'status', 'created_at']
    list_filter = ['is_admin', 'is_safety_officer', 'is_employee', 'department', 'status', 'gender', 'created_at']
    search_fields = ['username', 'name', 'phone', 'email', 'employee_number', 'safety_number', 'department', 'position']
    readonly_fields = ['id', 'employee_number', 'safety_number', 'years_of_service', 'completion_rate', 'last_login_time', 'created_at', 'updated_at']
    
    fieldsets = (
        ('账号信息', {
            'fields': ('id', 'username', 'password', 'status')
        }),
        ('角色设置', {
            'fields': ('is_admin', 'is_safety_officer', 'is_employee'),
            'description': '请选择用户的角色类型'
        }),
        ('基本信息', {
            'fields': ('name', 'gender', 'phone', 'email', 'department', 'position', 'hire_date', 'avatar', 'bio')
        }),
        ('管理员专属', {
            'fields': ('permissions', 'last_login_time'),
            'classes': ('collapse',),
            'description': '仅管理员角色需要填写'
        }),
        ('普通员工专属', {
            'fields': ('employee_number', 'contact', 'years_of_service', 'total_tasks', 'completed_tasks', 'completion_rate', 'avg_completion_time', 'last_remediation_date', 'evaluation'),
            'classes': ('collapse',),
            'description': '仅普通员工角色需要填写'
        }),
        ('安全员专属', {
            'fields': ('safety_number', 'license_number', 'management_scope', 'inspection_tasks', 'last_inspection_date'),
            'classes': ('collapse',),
            'description': '仅安全员角色需要填写'
        }),
        ('其他信息', {
            'fields': ('remarks', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )
    
    def get_identifier(self, obj):
        """获取标识符（员工编号或安全员编号）"""
        if obj.is_admin:
            return obj.username
        elif obj.is_safety_officer:
            return obj.safety_number or '未生成'
        elif obj.is_employee:
            return obj.employee_number or '未生成'
        return '-'
    get_identifier.short_description = '编号/用户名'
    
    def save_model(self, request, obj, form, change):
        """保存模型时处理密码"""
        if 'password' in form.changed_data:
            # 如果密码字段被修改，进行加密
            raw_password = form.cleaned_data['password']
            if not raw_password.startswith('pbkdf2_sha256$'):  # 判断是否已经加密
                obj.set_password(raw_password)
        super().save_model(request, obj, form, change)
